package com.hhu.userservice.service.imp;


import com.hhu.userservice.dao.UserLoginMapper;
import com.hhu.userservice.service.UserService;
import com.hhu.userservice.utils.RedisUtil;
import com.hhu.userservice.utils.TokenUtil;
import com.hhu.commonutils.pojo.*;
import com.hhu.commonutils.utils.Constants;
import com.hhu.commonutils.utils.LoginTipsEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

@Slf4j
@Service
public class UserServiceImp implements UserService {

    // Redis工具
    private RedisUtil redisUtil;

    private UserLoginMapper userLoginMapper;

    @Autowired
    public void setUserLoginMapper(UserLoginMapper userLoginMapper) {
        this.userLoginMapper = userLoginMapper;
    }

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    @Transactional
    public Result login(String userId, String passwordMD5) {
        try {
            UserInfo userInfo = userLoginMapper.getUser(userId, passwordMD5);
            log.info("验证登录信息：");
            if (!ObjectUtils.isEmpty(userInfo)) {
                // 生成token，并更新到redis中(没有就插入，有就更新)
                String newToken = TokenUtil.generateToken(userInfo.getUserId());
                redisUtil.set(newToken, userInfo, Constants.TOKEN_EXPIRED_TIME);
                // 返回最新的token信息
                return Result.ok().Data(newToken);
            } else {
                // 账号密码不对
                return Result.server_error().Message(LoginTipsEnum.WRONG_NAME_PWD.getTip());
            }

        } catch (RuntimeException e) {
            return Result.server_error().Message("登录失败\n：" + e.getMessage());
        }
    }
}
